<?php

namespace app\api\controller\v1\user;

use app\Request;
use app\services\user\UserServices;
use crmeb\services\CacheService;
use crmeb\services\ExpressService;
use think\facade\Db;


/**
 * 用户类
 * Class UserController
 * @package app\api\controller\store
 */
class UserController
{
    protected $services = NUll;

    /**
     * UserController constructor.
     * @param UserServices $services
     */
    public function __construct(UserServices $services) {
        $this->services = $services;
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return mixed
     */
    public function userInfo(Request $request) {
        $info = $request->user()->toArray();
        return app('json')->success($this->services->userInfo($info));
    }

    public function getUserShareCode(int $uid) {
        return app('json')->success(['invCode' => $this->services->get($uid)->self_inv_code]);
    }

    /**
     * 用户资金统计
     * @param Request $request
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function balance(Request $request) {
        $uid = (int)$request->uid();
        return app('json')->successful($this->services->balance($uid));
    }

    //my team
    public function user_team($uid, $request) {
        $limit = $request->get('limit') ? $request->get('limit') : 50;
        $page = $request->get('page') ? $request->get('page') : 1;
        $where = [
            ['spread_uid', '=', $uid],
            ['status', '=', 1]
        ];
        $list = Db::table('eb_user')->where($where)
            ->order('uid', 'desc')
            ->page($page, $limit)
            ->select()->toArray();
        $count = Db::table('eb_user')->where($where)->count();

        $first_uid = array_column($list, 'uid');
        $list_two = [];
        $count_two = 0;
        if ($first_uid) {
            $two_uid = implode(",", $first_uid);
            $where = "spread_uid in ($two_uid)";
            $list_two = Db::table('eb_user')->where($where)
                ->order('uid', 'desc')
                ->select()->toArray();
            $count_two = Db::table('eb_user')->where($where)->count();
        }
        $lSql = "select id,grade from eb_system_user_level where grade in (1,2,3,4) and is_del=0 ";
        $lInfo = Db::query($lSql);
        $lMap = array_column($lInfo, 'grade', 'id');
        if(!empty($list)){
            foreach ($list as &$v){
                $v['level']=!empty($lMap[$v['level']])?($lMap[$v['level']]-1):0;
            }
        }
        if(!empty($list_two)){
            foreach ($list_two as &$tv){
                $tv['level']=!empty($lMap[$tv['level']])?($lMap[$tv['level']]-1):0;
            }
        }
        $data = [
            'first' => ['data' => $list, 'total' => $count],
            'two' => ['data' => $list_two, 'total' => $count_two]
        ];
        return app('json')->success($data);
    }

    /**
     * 个人中心
     * @param Request $request
     * @return mixed
     */
    public function user(Request $request) {
        $user = $request->user()->toArray();
        $type = $request->get('type');
        if ($type == 'team') {
            return $this->user_team($user['uid'], $request);
        }

        return app('json')->success($this->services->personalHome($user, $request->tokenData()));
    }

    /**
     * 添加点赞
     *
     * @param Request $request
     * @return mixed
     */
//    public function like_add(Request $request)
//    {
//        list($id, $category) = UtilService::postMore([['id',0], ['category','product']], $request, true);
//        if(!$id || !is_numeric($id))  return app('json')->fail('参数错误');
//        $res = StoreProductRelation::productRelation($id,$request->uid(),'like',$category);
//        if(!$res) return  app('json')->fail(StoreProductRelation::getErrorInfo());
//        else return app('json')->successful();
//    }

    /**
     * 取消点赞
     *
     * @param Request $request
     * @return mixed
     */
//    public function like_del(Request $request)
//    {
//        list($id, $category) = UtilService::postMore([['id',0], ['category','product']], $request, true);
//        if(!$id || !is_numeric($id)) return app('json')->fail('参数错误');
//        $res = StoreProductRelation::unProductRelation($id, $request->uid(),'like',$category);
//        if(!$res) return app('json')->fail(StoreProductRelation::getErrorInfo());
//        else return app('json')->successful();
//    }


    /**
     * 获取活动状态
     * @return mixed
     */
    public function activity() {
        return app('json')->successful($this->services->activity());
    }

    /**
     * 用户修改信息
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request) {
        list($avatar, $nickname) = $request->postMore([
            ['avatar', ''],
            ['nickname', ''],
        ], true);
        if (!$avatar && $nickname == '') {
            return app('json')->fail('请输入昵称或者选择头像');
        }
        $uid = (int)$request->uid();
        if ($this->services->eidtNickname($uid, ['avatar' => $avatar, 'nickname' => $nickname])) {
            return app('json')->successful('修改成功');
        }
        return app('json')->fail('修改失败');
    }

    /**
     * 推广人排行
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rank(Request $request) {
        $data = $request->getMore([
            ['page', ''],
            ['limit', ''],
            ['type', '']
        ]);
        return app('json')->success($this->services->getRankList($data));
    }

    /**
     * 添加访问记录
     * @param Request $request
     * @return mixed
     */
    public function set_visit(Request $request) {
        $data = $request->postMore([
            ['url', ''],
            ['stay_time', 0]
        ]);
        if ($data['url'] == '') return app('json')->fail('未获取页面路径');
        $data['uid'] = (int)$request->uid();
        $data['ip'] = $request->ip();
        if ($this->services->setVisit($data)) {
            return app('json')->success('添加访问记录成功');
        } else {
            return app('json')->fail('添加访问记录失败');
        }
    }

    /**
     * 静默绑定推广人
     * @param Request $request
     * @return mixed
     */
    public function spread(Request $request) {
        [$spreadUid, $code] = $request->postMore([
            ['puid', 0],
            ['code', 0]
        ], true);
        $uid = (int)$request->uid();
        $this->services->spread($uid, (int)$spreadUid, $code);
        return app('json')->success();
    }

    /**
     * 推荐用户
     * @param Request $request
     * @return mixed
     *
     * grade == 0  获取一级推荐人
     * grade == 1  获取二级推荐人
     *
     * keyword 会员名称查询
     *
     * sort  childCount ASC/DESC  团队排序   numberCount ASC/DESC  金额排序  orderCount  ASC/DESC  订单排序
     */
    public function spread_people(Request $request) {
        $spreadInfo = $request->postMore([
            ['grade', 0],
            ['keyword', ''],
            ['sort', ''],
        ]);
        if (!in_array($spreadInfo['grade'], [0, 1])) {
            return app('json')->fail('等级错误');
        }
        $uid = $request->uid();
        return app('json')->successful($this->services->getUserSpreadGrade($uid, $spreadInfo['grade'], $spreadInfo['sort'], $spreadInfo['keyword']));
    }

    //快递查询
    public function kuaidi(Request $request) {
        $id = $request->post('id');
        $uid = $request->uid();
        //判断该订单是不是这个用户的
        $order = Db::table('eb_store_order')->where('id', $id)
            ->where('uid', $uid)
            ->whereNotNull('delivery_id')
            ->find();
        if ($order) {
            $cacheName = $order['order_id'] . $order['delivery_id'];
            if (!$result = CacheService::get($cacheName, null)) {
                $result = ExpressService::query($order['delivery_id']);
                if (is_array($result) &&
                    isset($result['result']) &&
                    isset($result['result']['deliverystatus']) &&
                    $result['result']['deliverystatus'] >= 3)
                    $cacheTime = 0;
                else
                    $cacheTime = 1800;
                CacheService::set($cacheName, $result, $cacheTime);
            }
            $data['delivery_name'] = $order['delivery_name'];
            $data['delivery_id'] = $order['delivery_id'];
            $data['result'] = $result['result']['list'] ?? [];
            return app('json')->success($data);
        } else {
            return app('json')->fail('查询错误');
        }
    }

    public function moveMoney(Request $request)
    {
        $uid = (int)$request->uid();
        [$account, $moveMoney] = $request->postMore([
            ['account', ''],
            ['moveMoney', 0],
        ], true);
        $userService = app()->make(UserServices::class);
        if ($userService->getMoveMoneyIsStart()) {
            return app('json')->fail('余额转账通道维护中!');
        }
        if (in_array($uid, $userService->getSniperUid())) {
            return app('json')->fail('该账号不能转出余额!');
        }
        if (!$account) {
            return app('json')->fail('转账账号不能为空!');
        }
        if (!$moveMoney) {
            return app('json')->fail('转账金额不能为空!');
        }
//        if ($moveMoney % 100 != 0) {
//            return app('json')->fail('转账金额只能为整百!');
//        }

        $myInfo = $userService->getUserInfo($uid);
        if(empty($myInfo)){
            return app('json')->fail('转账人信息异常!');
        }
        if($myInfo['account'] == $account){
            return app('json')->fail('不能给自己转账!');
        }
        if($myInfo['now_money']<$moveMoney){
            return app('json')->fail('转账金额不能大于个人金额!');
        }
        $moveIdInfo = $userService->getUser(['account|phone' => $account]);
        if (empty($moveIdInfo)) {
            return app('json')->fail('转账账号不存在!');
        }
        $rs=$userService->moveUserMoney($uid,$moveIdInfo['uid'],$myInfo['now_money'],$moveIdInfo['now_money'],$moveMoney, $account);
        if($rs){
            return app('json')->success('转账成功!');
        }
        return app('json')->fail('转账失败~');
    }

    //发团点迁移
    public function moveStartPoints(Request $request) {
        $uid = (int)$request->uid();
        [$account, $moviePoints] = $request->postMore([
            ['account', ''],
            ['moviePoints', 0],
        ], true);
        if (!$account) {
            return app('json')->fail('迁移账号不能为空!');
        }
        if (!$moviePoints) {
            return app('json')->fail('迁移开团点不能为空!');
        }
        $userService = app()->make(UserServices::class);
        $myInfo = $userService->getUserInfo($uid);
        if(empty($myInfo)){
            return app('json')->fail('迁移人信息异常!');
        }
        if($myInfo['account'] == $account){
            return app('json')->fail('不能给自己迁移开团点!');
        }
        if($myInfo['start_num']<$moviePoints){
            return app('json')->fail('迁移开团点不能大于个人开团点!');
        }
        $moveIdInfo = $userService->getUser(['account|phone' => $account]);
        if (empty($moveIdInfo)) {
            return app('json')->fail('迁移账号不存在!');
        }
        $rs=$userService->moveStartPoint($uid,$moveIdInfo['uid'],$myInfo['start_num'],$moveIdInfo['start_num'],$moviePoints);
        if($rs){
            return app('json')->success('迁移成功!');
        }
        return app('json')->fail('迁移失败~');

    }

    //获取发团点迁移明细
    public function getStartPointsLog(Request $request) {
        $uid = (int)$request->uid();
        [$page, $pageNum] = $request->postMore([
            ['page', 1],
            ['pageNum', 20],
        ], true);
        $userService = app()->make(UserServices::class);
        $data=$userService->getPointsLog($uid,$page,$pageNum);
        return app('json')->success($data);
    }

    //获取积分明细
    public function getUserPointsLog(Request $request) {
        $uid = (int)$request->uid();
        [$page, $pageNum] = $request->postMore([
            ['page', 1],
            ['pageNum', 20],
        ], true);
        $userService = app()->make(UserServices::class);
        $data=$userService->getUserPointsLog($uid,$page,$pageNum);
        return app('json')->success($data);
    }

    //获取个人排行榜积分订单表
    public function getRankOrderList(Request $request) {
        $uid = (int)$request->uid();
        [$page, $pageNum, $type] = $request->postMore([
            ['page', 1],
            ['pageNum', 20],
            ['status', 0],
        ], true);
        $userService = app()->make(UserServices::class);
        $uInfo = $userService->getUserInfo($uid);
        if (empty($uInfo)) {
            app('json')->success(['count' => 0, 'list' => []]);
        }
        $data = $userService->getRankOrderList($uInfo, $uid, $type, $page, $pageNum);
        return app('json')->success($data);

    }

    public function getUserPoints(Request $request)
    {
        $userService = app()->make(UserServices::class);
        $info = $userService->getUserInfo((int)$request->uid());
        return app('json')->success($info['points']);
    }

    //生成个人积分兑现订单表
    public function createRankMoneyOrder(Request $request) {
        $uid = (int)$request->uid();
        $userService = app()->make(UserServices::class);
        $configInfo = $userService->getRankConfig();//获取配置信息
        if (empty($configInfo)) {
            return app('json')->fail('当前不可参与积分兑换');
        }
        if (intval($configInfo['open_in_rank_money']) !== 1) {
            return app('json')->fail('当前不可参与积分兑换');
        }
        if (intval($configInfo['status']) !== 1) {
            return app('json')->fail('当前不可参与积分兑换');
        }
        if ($userService->getCountRankMoneyOrder($uid)) {
            return app('json')->fail('今日已提交积分兑换订单，请明日再来');
        }
        $uInfo = $userService->getUserInfo($uid);
        if ($uInfo['points'] < $configInfo['limit_integral']) {
            return app('json')->fail('积分不足');
        }
        $rs = $userService->createRankMoneyOrder($uInfo, $configInfo);
        if ($rs) {
            return app('json')->success('操作成功!');
        }
        return app('json')->success('操作失败');
    }

    //生成个人积分兑现订单表
    public function getRankMoneyOrder(Request $request) {
        $uid = (int)$request->uid();
        $userService = app()->make(UserServices::class);
        $orders = $userService->getRankMoneyOrder($uid);
        foreach ($orders as &$order) {
            $order['given_number'] = $userService->getGinvenRankMoney($uid, $order['id']);
            $order['all_number'] = $order['given_money'] + $order['given_number'];
        }
        return app('json')->successful($orders);
    }

    //生成个人排行榜积分订单表
    public function createRankOrder(Request $request) {
        //return app('json')->fail('当前不可进入排行榜');
        $uid = (int)$request->uid();
        $userService = app()->make(UserServices::class);
        $configInfo = $userService->getRankConfig();//获取配置信息
        if (empty($configInfo)) {
            return app('json')->fail('当前不可预约公排');
        }
        if (intval($configInfo['status']) !== 1) {
            return app('json')->fail('当前不可预约公排');
        }
        //获取当天总生成量
//        $total = $userService->getDateRankOrderCount();
//        if ($total >= $configInfo['max_times']) {
//            return app('json')->fail('已超当天最大订单量');
//        }
        $uInfo = $userService->getUserInfo($uid);
        if ($uInfo['points'] < $configInfo['limit_integral']) {
            return app('json')->fail('积分不足');
        }
        $rs = $userService->createRankOrder($uInfo, $configInfo);
        if ($rs) {
            return app('json')->success('操作成功!');
        }
        return app('json')->success('操作失败');
    }

    //撤销个人排行榜积分订单表
    public function cancelRankOrder(Request $request) {
        return app('json')->fail('当前不可撤销');
        $uid = (int)$request->uid();
        [$orderId] = $request->postMore([
            ['orderId', ''],
        ], true);
        if (!$orderId) {
            return app('json')->fail('订单号不能为空');
        }
        $userService = app()->make(UserServices::class);
        $orderInfo = $userService->checkRankOrderIsExist($uid, $orderId);
        if (!$orderInfo) {
            return app('json')->fail('订单号不存在');
        }
        if (!in_array($orderInfo['status'], [10, 40])) {
            return app('json')->fail('该订单不允许撤销');
        }
        $uInfo = $userService->getUserInfo($uid);
        $rs = $userService->cancelRankOrder($uInfo,$orderInfo);
        if ($rs) {
            return app('json')->success('操作成功!');
        }
        return app('json')->success('操作失败');

    }

    //释放个人排行榜积分订单表 扣积分得余额
    public function changeRankOrder(Request $request) {
        $uid = (int)$request->uid();
        [$orderId] = $request->postMore([
            ['orderId', ''],
        ], true);
        if (!$orderId) {
            return app('json')->fail('订单号不能为空');
        }
        $userService = app()->make(UserServices::class);
        $orderInfo = $userService->checkRankOrderIsExist($uid, $orderId);
        if (!$orderInfo) {
            return app('json')->fail('订单号不存在');
        }
        if ($orderInfo['status'] != 10) {
            return app('json')->fail('订单号状态异常');
        }
        $uInfo = $userService->getUserInfo($uid);
        $configInfo = $userService->getRankConfig();//获取配置信息
        $rs = $userService->changeRankOrder($uInfo,$orderInfo,$configInfo);
        if ($rs) {
            return app('json')->success('操作成功!');
        }
        return app('json')->success('操作失败');
    }
}
